<?php

namespace App\Component;

use App\Core\IdentityInterface;
use EasySwoole\Component\Di;
use EasySwoole\EasySwoole\Config;

class User extends BaseComponent{
    
    public $test = false;
    
    /** @var string|IdentityInterface */
    protected $_identityClass;
    
    /** @var IdentityInterface $_identity */
    protected $_identity;
    
    /**
     * @param string $identityClass 用户对应的对象类
     */
    public function __construct(string $identityClass){
        $this->setIdentityClass($identityClass);
    }
    
    /**
     * @return string
     */
    public function getIdentityClass(){
        return $this->_identityClass;
    }
    
    /**
     * @param string|IdentityInterface $identityClass
     */
    public function setIdentityClass($identityClass) : self{
        $this->_identityClass = $identityClass;
        return $this;
    }
    
    /**
     * @return IdentityInterface
     */
    public function getIdentity(){
        return $this->_identity;
    }
    
    /**
     * @param IdentityInterface $identity
     */
    public function setIdentity($identity) : self{
        $this->_identity = $identity;
        return $this;
    }
    
    public function login(IdentityInterface $identity){
        $this->setIdentity($identity);
        $identity->afterLogin();
        //todo 其他操作，如日志等
        return true;
    }
    
    /**
     * 判断是否登录
     * @return bool
     */
    public function isLogin(){
        return !empty($this->_identity);
    }
    
    /**
     * 通过JWT登陆
     * @param $jwtToken
     * @return bool
     * @throws \EasySwoole\Jwt\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function loginByJwt($jwtToken){
        //解析JWT
        /** @var Jwt $jwt */
        $jwt = Di::getInstance()->get('jwt');
        $parseJwt = $jwt->validateToken($jwtToken);

        $identity = $this->_identityClass::parseJwtData($parseJwt->data);

        $this->login($identity);
        return true;
    }
    
    
    public function generalJwtToken(){
        $expTime = $this->getIdentity()->getJwtExpiredTime();
        $expTime < time() + 300 && $expTime = time() + 604800;
        /** @var Jwt $jwt */
        $jwt = Di::getInstance()->get('jwt');
        if (Config::getInstance()->getConf('ENV') == 'dev' || Config::getInstance()->getConf('ENV') == 'test') {
            $expTime = time() + 3600000;
        }
        $jwtToken = $jwt->generalToken($this->getIdentity()->getJwtData(), $expTime);
        
        return $jwtToken;
    }
    
}
